<template>
	<view class="create-container">
		<!-- 顶部导航栏 -->
		<view class="nav-bar" :style="{ paddingTop: statusBarHeight + 'px' }">
			<view class="title">创建</view>
		</view>

		<!-- 内容区域 -->
		<scroll-view class="content-area" scroll-y>
			<!-- AI头像设置 -->
			<view class="avatar-section">
				<view class="avatar-box" @tap="chooseImage">
					<image class="avatar" :src="formData.icon" mode="aspectFill" />
					<view class="upload-icon">
						<text class="iconfont">+</text>
					</view>
				</view>
				<text class="avatar-text">AI 生成形象</text>
			</view>

			<!-- 表单部分 -->
			<view class="form-section">
				<!-- AI名称 -->
				<view class="form-item">
					<text class="label">名称</text>
					<input class="input" v-model="formData.name" placeholder="输入名称" placeholder-class="placeholder" />
				</view>

				<!-- 设定描述 -->
				<view class="form-item">
					<text class="label">设定描述</text>
					<textarea class="textarea" v-model="formData.description"
						placeholder="示例：你是一位经验丰富的英语老师，拥有激发学生学习热情的教学方法。你善于运用幽默和实际应用案例，使对话充满趣味。"
						placeholder-class="placeholder" :maxlength="500" />
				</view>

				<!-- 基础设置 -->
				<view class="form-group">
					<!-- 语言设置 -->
					<view class="setting-item" @tap="switchLanguage">
						<view class="left">
							<image class="icon" src="/static/语言.png" mode="aspectFit" />
							<text class="text">语言</text>
						</view>
						<view class="right">
							<text class="value">{{ formData.language }}</text>
							<text class="iconfont">></text>
						</view>
					</view>

					<!-- 可见性设置 -->
					<view class="setting-item" @tap="switchVisibility">
						<view class="left">
							<image class="icon" src="/static/商业化全球.png" mode="aspectFit" />
							<text class="text">{{ formData.visibility === 1 ? '公开·所有人可对话' : '私密·仅自己可见' }}</text>
						</view>
						<view class="right">
							<text class="iconfont">></text>
						</view>
					</view>
				</view>

				<!-- 更多高级设置 -->
				<view class="more-settings">
					<text class="text">更多高级设置</text>
				</view>
			</view>

			<!-- 创建按钮 -->
			<view class="create-button" :class="{ disabled: !isValid }" @tap="handleCreate">
				创建智能体
			</view>
		</scroll-view>

		<!-- 底部导航栏 -->
		<view class="tab-bar">
			<view v-for="(tab, index) in tabs" :key="index" class="tab-item" :class="{ active: currentTab === index }"
				@tap="switchTab(index)">
				<text class="iconfont" :class="tab.icon" />
				<text class="text">{{ tab.text }}</text>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		useDeviceStore
	} from '@/stores/modules/device'
	import deviceApi from '@/api/modules/device'
	const deviceStore = useDeviceStore()
	import {
		ref,
		computed
	} from 'vue'
	import {
		system
	} from '@/utils/system'

	// 状态栏高度
	const statusBarHeight = system.getStatusBarHeight()

	// 表单数据
	const formData = ref({
		name: '',
		icon: '',
		description: '',
		language: '中文',
		visibility: 0, // 默认私密
		systemPrompt: '', // 添加系统提示词字段
		category: '助手', // 添加分类字段
		tags: [] // 添加标签字段
	})

	// 当前选中的底部标签
	const currentTab = ref(2)

	// 底部标签配置
	const tabs = [{
			text: '对话',
			icon: 'icon-message'
		},
		{
			text: '发现',
			icon: 'icon-search'
		},
		{
			text: '创建',
			icon: 'icon-add'
		},
		{
			text: '通知',
			icon: 'icon-notification'
		},
		{
			text: '我的',
			icon: 'icon-user'
		}
	]

	// 表单验证
	const isValid = computed(() => {
		const nameValid = formData.value.name?.trim() &&
			formData.value.name.length >= 2 &&
			formData.value.name.length <= 64;

		const descValid = formData.value.description?.trim() &&
			formData.value.description.length <= 500;

		// 添加图标验证
		const iconValid = !!formData.value.icon;

		return nameValid && descValid && iconValid;
	});

	// 上传图片
	// 修改上传图片方法
	const chooseImage = () => {
		uni.chooseImage({
			count: 1,
			sizeType: ['compressed'],
			sourceType: ['album', 'camera'],
			success: async (res) => {
				try {
					// 显示上传中
					uni.showLoading({
						title: '上传中...',
						mask: true
					});

					// 上传图片
					const uploadRes = await deviceApi.uploadIcon(res.tempFilePaths[0]);

					// 解析返回结果
					if (uploadRes.code === 200) {
						formData.value.icon = uploadRes.data;
						uni.showToast({
							title: '上传成功',
							icon: 'success'
						});
					} else {
						throw new Error(uploadRes.message || '上传失败');
					}
				} catch (error) {
					console.error('上传图片失败:', error);
					uni.showToast({
						title: error.message || '上传失败',
						icon: 'none'
					});
				} finally {
					uni.hideLoading();
				}
			},
			fail: (error) => {
				console.error('选择图片失败:', error);
				uni.showToast({
					title: '选择图片失败',
					icon: 'none'
				});
			}
		});
	};

	// 切换语言
	const switchLanguage = () => {
		uni.showActionSheet({
			itemList: ['中文', 'English'],
			success: (res) => {
				formData.value.language = ['中文', 'English'][res.tapIndex]
			}
		})
	}

	// 切换可见性
	const switchVisibility = () => {
		uni.showActionSheet({
			itemList: ['公开·所有人可对话', '私密·仅自己可见'],
			success: (res) => {
				formData.value.visibility = res.tapIndex === 0 ? 1 : 0
			}
		})
	}

	// 底部导航切换
	const switchTab = (index) => {
		const routes = [
			'/pages/index/index',
			'/pages/discover/discover',
			'/pages/create/create',
			'/pages/notification/notification',
			'/pages/my/my'
		]

		uni.switchTab({
			url: routes[index]
		})
	}

	// 修改创建方法
	const handleCreate = async () => {
		if (!isValid.value) {
			uni.showToast({
				title: '请填写必要信息',
				icon: 'none'
			});
			return;
		}

		// 检查是否上传了头像
		if (!formData.value.icon) {
			uni.showToast({
				title: '请上传AI头像',
				icon: 'none'
			});
			return;
		}

		uni.showLoading({
			title: '创建中...',
			mask: true
		});

		try {
			const res = await deviceStore.createDevice({
				name: formData.value.name,
				description: formData.value.description,
				icon: formData.value.icon, // 使用上传后的URL
				visibility: formData.value.visibility,
				category: '助手',
				tags: []
			});

			if (res.code === 200) {
				uni.hideLoading();
				uni.showToast({
					title: '创建成功',
					icon: 'success'
				});

				setTimeout(() => {
					uni.switchTab({
						url: '/pages/index/index'
					});
				}, 1500);
			} else {
				throw new Error(res.message || '创建失败');
			}

		} catch (error) {
			console.error('创建智能体失败:', error);
			uni.hideLoading();
			uni.showToast({
				title: error.message || '创建失败',
				icon: 'none',
				duration: 2000
			});
		}
	};
</script>

<style lang="scss">
	.create-container {
		min-height: 100vh;
		background: #F5F5F5;
		display: flex;
		flex-direction: column;

		.nav-bar {
			background: #fff;
			height: 88rpx;
			display: flex;
			align-items: center;
			padding: 0 30rpx;
			border-bottom: 1rpx solid #eee;

			.title {
				font-size: 36rpx;
				font-weight: 600;
				color: #333;
			}
		}

		.content-area {
			flex: 1;
			padding-bottom: 110rpx;
		}

		.avatar-section {
			padding: 60rpx 0;
			display: flex;
			flex-direction: column;
			align-items: center;
			background: #fff;

			.avatar-box {
				width: 160rpx;
				height: 160rpx;
				position: relative;
				margin-bottom: 20rpx;

				.avatar {
					width: 100%;
					height: 100%;
					border-radius: 50%;
					background-color: #f0f0f0;
				}

				.upload-icon {
					position: absolute;
					right: -10rpx;
					bottom: -10rpx;
					width: 60rpx;
					height: 60rpx;
					background: #007AFF;
					border-radius: 50%;
					display: flex;
					align-items: center;
					justify-content: center;

					.iconfont {
						color: #fff;
						font-size: 40rpx;
					}
				}
			}

			.avatar-text {
				font-size: 28rpx;
				color: #666;
			}
		}

		.form-section {
			margin-top: 20rpx;
			background: #fff;
			padding: 0 30rpx;

			.form-item {
				padding: 10rpx 0;
				border-bottom: 1rpx solid #eee;

				.label {
					font-size: 32rpx;
					font-weight: 500;
					margin-bottom: 20rpx;
					display: block;
				}

				.input {
					width: 100%;
					height: 50rpx;
					font-size: 30rpx;
				}

				.textarea {
					width: 100%;
					height: 200rpx;
					font-size: 28rpx;
				}

				.placeholder {
					color: #999;
				}
			}

			.form-group {
				.setting-item {
					height: 100rpx;
					display: flex;
					align-items: center;
					justify-content: space-between;
					border-bottom: 1rpx solid #eee;

					.left {
						display: flex;
						align-items: center;

						.icon {
							width: 40rpx;
							height: 40rpx;
							margin-right: 20rpx;
						}

						.text {
							font-size: 30rpx;
						}
					}

					.right {
						display: flex;
						align-items: center;

						.value {
							font-size: 28rpx;
							color: #666;
							margin-right: 10rpx;
						}

						.iconfont {
							color: #999;
							font-size: 28rpx;
						}
					}
				}
			}

			.more-settings {
				padding: 30rpx 0;
				text-align: center;

				.text {
					font-size: 28rpx;
					color: #007AFF;
				}
			}
		}

		.create-button {
			margin: 60rpx 30rpx;
			height: 88rpx;
			line-height: 88rpx;
			text-align: center;
			background: #007AFF;
			color: #fff;
			font-size: 32rpx;
			border-radius: 44rpx;

			&.disabled {
				opacity: 0.6;
			}
		}

		.tab-bar {
			position: fixed;
			left: 0;
			right: 0;
			bottom: 0;
			height: 110rpx;
			background: #fff;
			display: flex;
			align-items: center;
			border-top: 1rpx solid #eee;
			padding-bottom: env(safe-area-inset-bottom);

			.tab-item {
				flex: 1;
				display: flex;
				flex-direction: column;
				align-items: center;
				color: #999;

				.iconfont {
					font-size: 48rpx;
					margin-bottom: 6rpx;
				}

				.text {
					font-size: 24rpx;
				}

				&.active {
					color: #007AFF;
				}
			}
		}
	}
</style>